/**
 * ===========================================
 * Project: cyou-framework
 * ===========================================
 * Package: com.cyou.framework.baseutil
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.framework.util;

/**
 * <p>TemplateUtility</p>
 *
 * @since 1.0
 * @version 1.0, 2012-11-29
 * @author zhangxingkai
 */
public class TemplateUtility {
	
	/**
     * <p>{@code TemplateUtility} instances should NOT be constructed in
     * standard programming. Instead, the class should be used as
     * {@code TemplateUtility.process("Hello ${0}", ["Tom"]);}.</p>
     *
     * <p>This constructor is public to permit tools that require a JavaBean
     * instance to operate.</p>
     */
	public TemplateUtility() {
		super();
	}
	
	/**
	 * <p>Process {@code source} to generate the result string.
	 * It will replace all the parameter placeholders with the parameter values.</p>
	 * 
	 * <p>the format of the parameter placeholder: ${number}.
	 * And the {@code source} can have more than one same placeholder, for example,
	 * Hello ${0}, Today is ${1}! Oh, are you ${0}?</p>
	 * 
	 * <pre>
	 * String source = "Today is ${1}, hello world, ${0}!";
	 * String result = TemplateUtility.process(source, {"Tom", "Friday"});
	 * result == "Today is Friday, hello world, Tom!";
	 * </pre>
	 * 
	 * @param source the source string with any placeholder
	 * @return the trimmed String, or an empty String if {@code null} input
	 * @since 1.0
	 */
	public static String process(String source, String[] params) {
		if (params == null || params.length == 0) {
			return source;
		}
		int length = params.length;
		String[] paramPlaceHolders = new String[length];
		for (int index = 0; index < length; index++) {
			paramPlaceHolders[index] = "${" + index + "}";
		}
		return StringUtility.replaceEach(source, paramPlaceHolders, params);
	}

}
